package com.study.manage.mvc.v2;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.NewsRepository;
import com.study.manage.domain.News;
import com.study.manage.domain.enumm.EvaluateNewType;
import com.study.manage.domain.enumm.LiveDieState;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.SessionUser;
import com.study.manage.mvc.common.UploadController;
import com.study.manage.utils.MapUtils;



@Controller
@RequestMapping("/v2/plugin")
public class V2PluginController extends UploadController {


    @Autowired
    private NewsRepository newsRepository;

    @ResponseBody
    @RequestMapping(path = "news", method = RequestMethod.GET)
    public AjaxResponse news(String name, @DateTimeFormat(pattern = "yyyy-MM-dd") Date date,
            EvaluateNewType type,
            @PageableDefault(sort = {"id"}, direction = Direction.DESC) Pageable pageable) {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getUserInfo();
        Page<News> page = newsRepository.findByTitleAndDateAndUserIdAndType(name, date,
                LiveDieState.LIVE, su.getId(), type, pageable);
        return ajax.setObj(page.map(new Converter<News, Map<String, Object>>() {
            @Override
            public Map<String, Object> convert(News o) {
                // 基本数据
                Map<String, Object> map =
                        MapUtils.convert(o, "title", "type", "pic", "id", "createdAt");
                if (o.type == EvaluateNewType.NOTICE) {
                    map.put("title", o.content);
                }
                map.put("typeDesc", o.type.desc);
                return map;
            }
        }));
    }

}
